<template>
  <div class="user-info">
    <el-descriptions class="margin-top" title="个人信息" :column="4" border>
      <template slot="extra">
        <el-button type="primary" size="small" @click="editUserInfo">操作</el-button>
      </template>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>用户名
        </template>
        {{userInfo.name}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-mobile-phone"></i>手机号
        </template>
        {{userInfo.phone}}
      </el-descriptions-item>
      <el-descriptions-item span="2">
        <template slot="label">
          <i class="el-icon-location-outline"></i>居住地
        </template>
        {{userInfo.address}}
      </el-descriptions-item>
      <el-descriptions-item >
        <template slot="label">
          <i class="el-icon-tickets"></i>头像
        </template>
        <el-avatar shape="square" :size="100" fit="fit" :src="userInfo.avatar"></el-avatar>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-office-building"></i>
          邮箱
        </template>
       {{userInfo.email}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-office-building"></i>
          性别
        </template>
        {{userInfo.gender?'女':'男'}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-office-building"></i>
          创建时间
        </template>
        {{userInfo.createTime}}
      </el-descriptions-item>
    </el-descriptions>
    <!--修改个人信息-->
    <el-dialog
        title="个人信息"
        :visible.sync="showEditUserInfo"
        :close-on-click-modal="false"
        width="55%"
        :before-close="closeEditUserInfo">
      <el-form ref="userForm" status-icon :rules="userRules" :model="editUser" label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editUser.username"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="editUser.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editUser.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="editUser.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio v-model="editUser.gender" :label="false" border>男</el-radio>
              <el-radio v-model="editUser.gender" :label="true" border>女</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-input v-model="editUser.createTime" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editUser.address"></el-input>
        </el-form-item>
<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="新密码" prop="newPassword">-->
<!--              <el-input type="password" v-model="editUser.newPassword"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="再次确认" prop="againPassword">-->
<!--              <el-input type="password" v-model="editUser.againPassword"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-form-item label="修改头像">
          <el-avatar shape="square" :size="100" fit="fit" :src="editUser.avatar"></el-avatar>
          <el-upload class="avatar-uploader" style="display: inline-block;" ref="userAvatar"
              action="#" :auto-upload="false" :show-file-list="false" :limit="2" :on-change="changeAvatar">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="closeEditUserInfo">取 消</el-button>
      <el-button type="primary" @click="okEditUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <admin-footer/>
  </div>
</template>

<script>
import {getUserInfoByMySelf, updateUserByMySelf} from "@/network/adminUser";
import {SET_USERINFO} from "@/store/mutations-type";
import AdminFooter from "@/components/conment/adminfooter/AdminFooter";
export default {
  name: "UserInfo",
  components: {AdminFooter},
  data() {
    // let checkNewPassword = (rule,value,callback)=>{
    //   if (value === undefined && this.editUser.againPassword === undefined){
    //     callback();
    //   }
    //   else if (value === undefined && this.editUser.againPassword !== undefined)
    //     callback(new Error('密码不能为空!'));
    //   if (value.length < 5 || value.length > 15) {
    //     callback(new Error('长度在5-15'));
    //   } else {
    //     if (this.editUser.againPassword !== '') {
    //       this.$refs.userForm.validateField('againPassword');
    //     }
    //     callback();
    //   }
    // }
    // let checkAgainPassword = (rule,value,callback)=>{
    //   if (value === undefined && this.editUser.newPassword === undefined){
    //     callback();
    //   }
    //   else if (value === undefined && this.editUser.newPassword !== undefined)
    //     callback(new Error('密码不能为空!'));
    //   if (value.length<5 || value.length>15) {
    //     callback(new Error('长度在5-15'));
    //   } else if (value !== this.editUser.newPassword) {
    //     callback(new Error('两次输入密码不一致!'));
    //   } else {
    //     callback();
    //   }
    // }
    return {
      userRules:{
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入正确的电话', trigger: 'blur' },
          { min: 7, max: 11, message: '长度在 7 到 11 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min: 4, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
        // newPassword: [
        //   {validator:checkNewPassword, trigger: 'blur'}
        // ],
        // againPassword: [
        //   {validator:checkAgainPassword, trigger: 'blur'}
        // ]
      },
      userInfo:{},
      editUser:{},
      showEditUserInfo:false,
    }
  },
  methods: {
    //头像文件上传之前的检测
    checkUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isGIF = file.type === 'image/gif';
      const isPNG = file.type === 'image/png';
      const isBMP = file.type === 'image/bmp';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false
      }
      return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
    },
    //修改信息
    editUserInfo(){
      this.editUser = JSON.parse(JSON.stringify(this.userInfo))
      // this.$set(this.editUser,'newPassword','')
      // this.$set(this.editUser,'againPassword','')
      this.showEditUserInfo=true
    },
    //头像有修改
    changeAvatar(file, fileList){
      if (fileList.length!==1)
        fileList = fileList.splice(-1)
      if (this.checkUpload(file.raw)) {//文件类型检查通过
        this.editUser.avatar = URL.createObjectURL(file.raw)
      }
    },
    closeEditUserInfo(){
      this.showEditUserInfo = false
      this.$refs.userForm.clearValidate()
    },
    //确认修改
    okEditUserInfo:async function(){
      await this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          if (JSON.stringify(this.userInfo)!==JSON.stringify(this.editUser)){
            let form = new FormData()
            if (this.$refs.userAvatar.uploadFiles.length!==0)
              form.append('userAvatar',this.$refs.userAvatar.uploadFiles[0].raw)
            this.$delete(this.editUser, "createTime")
            for (let i in this.editUser)//将属性遍历到FormData中
              form.append(i, this.editUser[i])
            await updateUserByMySelf(form).then(async res => {
              getUserInfoByMySelf().then(res=>{
                //更新store里面的数据
                this.$store.commit(SET_USERINFO,res.data.data)
                this.userInfo = res.data.data
              })
              this.$message.success('更新成功')
            })
          }
          this.closeEditUserInfo();
        } else {
          console.log('表单验证未通过')
        }
      })
    }
  },
  activated() {
    this.userInfo = this.$store.getters.getUserInfo
  },
  created() {
    this.userInfo = this.$store.getters.getUserInfo
  }
}
</script>

<style scoped>
  h2 {
    display: inline-block;
    margin: 0 auto;
  }
  .avatar-uploader .el-upload {
    display: inline-block;
    margin: 0 auto;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    position: absolute;
    font-size: 28px;
    top: 0;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: inline-block;
  }
</style>